package com.sctvcloud.zhaohua_sd.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.application.Cache;
import com.sctvcloud.zhaohua_sd.application.Constances;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.beans.FCityItem;
import com.sctvcloud.zhaohua_sd.beans.FCityNews;
import com.sctvcloud.zhaohua_sd.beans.FCityState;
import com.sctvcloud.zhaohua_sd.beans.FScribeState;
import com.sctvcloud.zhaohua_sd.beans.FUsers;
import com.sctvcloud.zhaohua_sd.beans.GovBean;
import com.sctvcloud.zhaohua_sd.beans.GovItemBean;
import com.sctvcloud.zhaohua_sd.beans.NewsItem;
import com.sctvcloud.zhaohua_sd.http.AbsListNetCallback;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.http.ParamsEditor;
import com.sctvcloud.zhaohua_sd.ui.activities.CityStaHomepageActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.GovDetailActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.LoginActivity;
import com.sctvcloud.zhaohua_sd.ui.activities.ShareDetailActivity;
import com.sctvcloud.zhaohua_sd.ui.adapter.CityStaChannelAdapter;
import com.sctvcloud.zhaohua_sd.ui.adapter.CityStateNewsAdapter;
import com.sctvcloud.zhaohua_sd.ui.adapter.GovStuffAdapter;
import com.sctvcloud.zhaohua_sd.ui.adapter.holder.GovStuffHolder;
import com.sctvcloud.zhaohua_sd.ui.adapter.holder.LiveHomeItemHolder;
import com.sctvcloud.zhaohua_sd.ui.utils.SkipUtil;
import com.sctvcloud.zhaohua_sd.utils.ListTypeUtils;
import com.sctvcloud.zhaohua_sd.utils.UserManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.sctvcloud.zhaohua_sd.base.BaseActivity.DO_UP_POS;

/**
 * Created by Administrator on 2017/7/17 0017.
 * 首页政务界面
 */
public class GovStuffFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener
        , CanRefreshLayout.IScrollView {
    @BindView(R.id.city_state_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.city_news_list)
    protected RecyclerView news_list;
    private LinearLayoutManager manager;
    private GovStuffAdapter govAdapter;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout detail;
    private int currentNews = 0;
    private int pageAll = 0;
    private String newsUrl;
    private List<GovItemBean> govList;
    private String token;
    private String userId;
    public static final int REQUEST_CODE = 1;
    public static final int REQUEST_LOGIN_CODE = 101;
    private boolean isSubscribe;
    private int types; //types 1 订阅 2取消订阅
    private String institutionId;
    GovBean all_data;
    List<FCityState> all_subscribeList = new ArrayList<FCityState>();
    String channelId;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_gov_stuff, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        news_list.setItemAnimator(new DefaultItemAnimator());
        news_list.setLayoutManager(manager);
        refreshLayout.autoRefresh();
        detail.setiScrollView(this);
        Bundle arguments = getArguments();
        if (arguments != null) {
            channelId = arguments.getString("channelId", "");
        }
    }


    @Override
    public void onRefresh() {
        getGovList();
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            onRefresh();
        }

    }

    /**
     * 获取市州机构列表
     */
    private void getGovList() {

        HashMap<String, Object> param = new HashMap<>();
        param.put("siteNumber",Constances.SITE_ID);
        param.put("nodeId",channelId);

        NetUtils.getNetAdapter().getGovList(getOwnerName(), param, new AbsNetCallBack<GovBean>(GovBean.class) {
            @Override
            public void onSuc(GovBean item) {
                if (item != null) {
                    all_data = item;
                }
                all_subscribeList.clear();

                if(null != item.getDataList() && item.getDataList().size()>0){
                    getsubcribeList();
                }

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
    }


    /**
     * 订阅或取消订阅某个机构数据
     * @param cityState
     */
    private void getSubscribeStateChange(final GovItemBean cityState) {
        if (cityState == null) {
            return;
        }
        if (UserManager.getInstance().isLogin()) {
            FUsers user = UserManager.getInstance().getUser();
            token = user.getToken();
            userId = user.getUserId();
            isSubscribe = cityState.isSubscibe();
            institutionId = cityState.getInstitutionId();
            if (isSubscribe) {
                types = 2;
            } else {
                types = 1;
            }
            ParamsEditor pe = new ParamsEditor();
//            pe.put("userId", userId);
//            ArrayMap<String, Object> params = new ArrayMap<>();
            pe.put("institutionId", institutionId);
            pe.put("type", types); //1订阅 2 取消订阅
            pe.put("userId", userId);
            NetUtils.getNetAdapter().getSubscribeState(getOwnerName(), pe.getEncryptedParams(token)
                    , new AbsNetCallBack<FScribeState>(FScribeState.class) {
                        @Override
                        public void onSuc(FScribeState scribeState) {
                            isSubscribe = !isSubscribe;
                            // cityState.setSubscibe(isSubscribe);
                            for (int i = 0; i < govList.size(); i++) {
                                if (cityState.getInstitutionId().equals(govList.get(i).getInstitutionId())) {
                                    govList.get(i).setSubscibe(isSubscribe);
                                    if (types == 1) {
                                        govList.get(i).setType(1);
                                    } else if (types == 2) {
                                        govList.get(i).setType(0);
                                    }

                                }
                            }

                          //  Collections.sort(govList);
                            govList = sortList(govList);
                            govAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public void onError(Throwable ex, String errorMsg) {
                            super.onError(ex, errorMsg);
                            JLog.e("====error=" + errorMsg);
                            toast(errorMsg);
                        }
                    });

        } else {
            Intent intent = new Intent(getContext(), LoginActivity.class);
            startActivityForResult(intent, REQUEST_LOGIN_CODE);
        }

    }



    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
    }

    OnItemInternalClick newsItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {

            if(itemView.getId() ==R.id.li_one || itemView.getId() == R.id.li_two) {

                NewsItem newsItem = null;
                if (view == null) {
                    newsItem = (NewsItem) itemView.getTag(R.id.adapter_item_data_key);
                } else {
                    newsItem = (NewsItem) itemView.getTag(R.id.adapter_item_data_key);
                }
                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                pairs.add(new Pair<>("页面", "首页"));
                pairs.add(new Pair<>("栏目", "政务"));
                ArrayList<Pair<String, String>> pairsMap = new ArrayList<>();
                pairsMap.addAll(pairs);
                pairsMap.add(new Pair<>("行为类型", "点击"));
                GridsumWebDissector.getInstance().trackEvent(GovStuffFragment.this, "", newsItem.getNewsTitle(), "", 200, pairsMap);
                HashMap<String, String> map = new HashMap<>();
                for (Pair<String, String> p : pairs) {
                    map.put(p.first, p.second);
                }
                if (newsItem != null) {
                    //进入相应的新闻详情页面
                    SkipUtil.skipWithNewsItem(getContext(), newsItem, map);
                } else {
                    toast("数据错误");
                }
            }else if(itemView.getId() ==R.id.li_all){

                GovItemBean newsItem = null;
                if (view == null) {
                    newsItem = (GovItemBean) itemView.getTag(R.id.adapter_item_data_key);
                } else {
                    newsItem = (GovItemBean) itemView.getTag(R.id.adapter_item_data_key);
                }
//
                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                pairs.add(new Pair<>("页面", "首页"));
                pairs.add(new Pair<>("栏目", "政务"));
                ArrayList<Pair<String, String>> pairsMap = new ArrayList<>();
                pairsMap.addAll(pairs);
                pairsMap.add(new Pair<>("行为类型", "点击"));
                GridsumWebDissector.getInstance().trackEvent(GovStuffFragment.this, "", newsItem.getInstitutionName(), "", 200, pairsMap);

                Intent intent = new Intent(getActivity(), GovDetailActivity.class);
                intent.putExtra(EX_DATA, newsItem);
                startActivityForResult(intent, REQUEST_CODE);



            }
            else if(itemView.getId() == R.id.item_city_state_channel_status){
                GovItemBean item = null;
                if (view == null) {
                    item = (GovItemBean) itemView.getTag(R.id.adapter_item_data_key);
                } else {
                    item = (GovItemBean) itemView.getTag(R.id.adapter_item_data_key);
                }
                getSubscribeStateChange(item);
                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                pairs.add(new Pair<>("页面", "首页"));
                pairs.add(new Pair<>("栏目", "政务"));
                pairs.add(new Pair<>("位置", item.getInstitutionName()));
                if (item.isSubscibe()) {
                    pairs.add(new Pair<>("行为类型", "取消订阅"));
                } else {
                    pairs.add(new Pair<>("行为类型", "点击订阅"));
                }
                GridsumWebDissector.getInstance().trackEvent(getActivity(), "", item.getInstitutionName(), "", 200, pairs);

            }else{

            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            onRefresh();
        }
        if (requestCode == REQUEST_LOGIN_CODE) {
            onRefresh();
        }

    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        boolean b = ViewCompat.canScrollVertically(news_list, -1);
        JLog.e("ggag   " + b);
        return b;
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        boolean b = ViewCompat.canScrollVertically(news_list, 1);
        JLog.e("ggag   " + b);
        return b;
    }


    /**
     * 获取用户订阅的机构
     */
    private void getsubcribeList() {
        if (UserManager.getInstance().isLogin()) {
            FUsers user = UserManager.getInstance().getUser();
            token = user.getToken();
            userId = user.getUserId();
        }else{
            compareSubscribe(all_data.getDataList(), null);
        }

        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(userId)) {
            ParamsEditor pe = new ParamsEditor();
            pe.put("userId", userId);
            pe.put("nodeId", channelId);
            NetUtils.getNetAdapter().getUserOrganList(getOwnerName(), pe.getEncryptedParams(token)
                    , new AbsListNetCallback<FCityState>(ListTypeUtils.FCityState()) {
                        @Override
                        public void onSuc(List<FCityState> fCityStates) {
                                all_subscribeList.addAll(fCityStates);
                                compareSubscribe(all_data.getDataList(), all_subscribeList);
                        }

                        @Override
                        public void onError(Throwable ex, String errorMsg) {
                            super.onError(ex, errorMsg);
                            compareSubscribe(all_data.getDataList(), null);
                        }
                    });
        } else {
            JLog.e("====" + "你还没有登录");
        }
    }

    /**
     * 对比那些机构已订阅，并刷新机构列表中的数据状态
     *
     * @param list
     * @param subList
     */
    private void compareSubscribe(List<GovItemBean> list, List<FCityState> subList) {
        if(null !=subList) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSubscibe(false);
                list.get(i).setType(0);
                for (int j = 0; j < subList.size(); j++) {
                    if (list.get(i).getInstitutionId().equalsIgnoreCase(subList.get(j).getInstitutionId())) {
                        list.get(i).setSubscibe(true);
                        list.get(i).setType(1);
                    }
                }
            }
        }
     //   Collections.sort(list);
        govList  = sortList(list);
        if (govAdapter == null) {
            govAdapter = new GovStuffAdapter(getContext(), govList).setItemInternalClick(newsItemClick);
            news_list.setAdapter(govAdapter);
        }
        else{
            govAdapter.clean();
            govAdapter.setData(govList);
        }
        govAdapter.notifyDataSetChanged();

    }


    private List<GovItemBean> sortList(List<GovItemBean> list){
        List<GovItemBean> ordered = new ArrayList<GovItemBean>();
        List<GovItemBean> unordered = new ArrayList<GovItemBean>();
        List<GovItemBean> all = new ArrayList<GovItemBean>();

        for(GovItemBean ii : list){
                if(ii.isSubscibe()) {
                    ordered.add(ii);
                }else{
                    unordered.add(ii);
                }
        }

        all.addAll(ordered);
        all.addAll(unordered);

        return all;
    }





}
